/*
 * Copyright 1999-2004 Carnegie Mellon University.
 * Portions Copyright 2004 Sun Microsystems, Inc.
 * Portions Copyright 2004 Mitsubishi Electric Research Laboratories.
 * All Rights Reserved.  Use is subject to license terms.
 *
 * See the file "license.terms" for information on usage and
 * redistribution of this file, and for a DISCLAIMER OF ALL
 * WARRANTIES.
 *
 */

package javamail.speech;

import edu.cmu.sphinx.frontend.util.AudioFileDataSource;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/** A simple example that shows how to transcribe a continuous audio file that has multiple utterances in it. */
public class speechTranscriber {

    // required for testing only.
    public static List<String> unitTestBuffer = new ArrayList<String>();
    public static String recognized = "";


    public static String transcribe(String name) {
        URL audioURL, configURL;

        try {
            audioURL = new File(name).toURI().toURL();
            configURL = new File("config.xml").toURI().toURL();
        } catch (MalformedURLException e) {
            System.err.println("speechTranscriber:transcribe()-Audio file or the config file not found! "+e.getMessage());
            return null;
        } catch (Exception e) {
            System.err.println("speechTranscriber:transcribe()-Error occured: "+e.getMessage());
            return null;
        }

        ConfigurationManager cm = new ConfigurationManager(configURL);
        Recognizer recognizer = (Recognizer) cm.lookup("recognizer");

        /* allocate the resource necessary for the recognizer */
        recognizer.allocate();

        // configure the audio input for the recognizer
        AudioFileDataSource dataSource = (AudioFileDataSource) cm.lookup("audioFileDataSource");
        dataSource.setAudioFile(audioURL, null);

        // Loop unitl last utterance in the audio file has been decoded, in which case the recognizer will return null.
        Result result;
        try {
            while ((result = recognizer.recognize())!= null) {
                    String resultText = result.getBestResultNoFiller();
                    recognized += resultText;
                    System.err.println("speechTranscriber:transcribe()-Results:"+resultText);
                    unitTestBuffer.add(resultText);
            }
        } catch (Exception e) {
            System.err.println("speechTranscriber:transcribe()-Error occured: "+e.getMessage());
            e.printStackTrace();
        }
        return recognized;
    }
}
